'use client'
import Image from 'next/image'
import React, { useState, useCallback, useEffect } from 'react'
import { Search, Trash2, Pencil, Filter, Upload, Users } from 'lucide-react'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { clsx } from 'clsx'
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { commonService } from '@/services'
import { useGlobalMethods } from '@/hooks/useGlobalMethods'
import { useFileStore, type FileItem, type FilterState } from '@/stores/fileStore'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import Pagination from '@/components/Pagination'
import { type ResourceQuery } from '@/services'
import UploadCard from './components/UploadCard'
import { useTranslation } from 'react-i18next'
import { cn } from '@/lib/utils'

const ITEMS_PER_PAGE = 10

const FileList = () => {
  const { t } = useTranslation('mysource')
  const { handlePreview } = useGlobalMethods()
  const [searchText, setSearchText] = useState('')
  const [selectedFiles, setSelectedFiles] = useState<string[]>([])
  const [isAllSelected, setIsAllSelected] = useState(false)
  const [openUpload, setOpenUpload] = useState(false)
  const [editItem, setEditItem] = useState<null | FileItem>(null)

  const { files, tagList, totalRecords, fetchFiles, getTagList } = useFileStore()
  const [currentPage, setCurrentPage] = useState(1)
  const [totalPages, setTotalPages] = useState(0)

  // 初始化时使用固定值
  const [filters, setFilters] = useState<FilterState>({
    type: '全部', // 保持原有的中文键值
    timeRange: '全部',
    sortBy: '时间降序',
    tags: '',
    public: '',
  })

  const buildQuery = useCallback(
    (
      pageNum: number = 1,
      useCusFilters?: FilterState,
      useCusText?: string,
    ): ResourceQuery => {
      const currentFilter = useCusFilters || filters
      const currentText = useCusText || searchText
      const query: ResourceQuery = {
        keywords: currentText,
        exts: currentFilter.type === '全部' ? '' : currentFilter.type,
        pageNum,
        pageSize: ITEMS_PER_PAGE,
        order_by: currentFilter.sortBy.includes('时间降序') ? 'created_at' : 'name',
        direction: currentFilter.sortBy.includes('升序') ? 'asc' : 'desc',
        public:
          currentFilter.public === ''
            ? undefined
            : currentFilter.public === '1'
              ? 1
              : 0,
        tags: currentFilter.tags === 'all' ? '' : currentFilter.tags,
      }

      // 添加时间范围参数
      const now = new Date()
      switch (currentFilter.timeRange) {
        case '今天':
          query.created_at_start = new Date(now.setHours(0, 0, 0, 0)).toISOString()
          query.created_at_end = new Date(
            now.setHours(23, 59, 59, 999),
          ).toISOString()
          break
        case '最近7天':
          const sevenDaysAgo = new Date(now)
          sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)
          query.created_at_start = sevenDaysAgo.toISOString()
          query.created_at_end = now.toISOString()
          break
        case '最近30天':
          const thirtyDaysAgo = new Date(now)
          thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30)
          query.created_at_start = thirtyDaysAgo.toISOString()
          query.created_at_end = now.toISOString()
          break
        case '更早':
          const monthsAgo = new Date(now)
          monthsAgo.setMonth(monthsAgo.getMonth() - 3)
          query.created_at_end = monthsAgo.toISOString()
          break
        default:
          break
      }

      return query
    },
    [filters, searchText],
  )

  // 修改搜索函数
  const handleSearch = useCallback(() => {
    setCurrentPage(1)
    setSelectedFiles([])
    fetchFiles(buildQuery(1))
  }, [fetchFiles, buildQuery])

  // 添加页面切换处理函数
  const handlePageChange = useCallback(
    (page: number = 1) => {
      setCurrentPage(page)
      fetchFiles(buildQuery(page))
    },
    [fetchFiles, buildQuery],
  )

  // 监听总记录数变化，计算总页数
  useEffect(() => {
    setTotalPages(Math.ceil(totalRecords / ITEMS_PER_PAGE))
  }, [totalRecords])

  useEffect(() => {
    handleSearch()
    getTagList()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  // 上传完成后
  const handleUpload = useCallback(() => {
    setEditItem(null)
    handleSearch()
  }, [handleSearch])

  // 处理单个文件选择
  const handleSelect = useCallback((fileId: string, checked: boolean) => {
    setSelectedFiles((prev) => {
      if (checked) {
        return [...prev, fileId]
      }
      return prev.filter((id) => id !== fileId)
    })
  }, [])

  // 处理删除
  const handleDelete = useCallback(async () => {
    if (selectedFiles.length === 0) return
    const delList = files.filter((file) => selectedFiles.includes(file.id))
    const ids = delList.map((v) => v.id).join(',')
    await commonService.resourceDelete(ids)
    await handleSearch()
  }, [selectedFiles, files, handleSearch])

  /******************** 新增过滤状态 ********************/

  // 处理全选/取消全选
  const handleSelectAll = useCallback(
    (checked: boolean) => {
      if (checked) {
        setSelectedFiles(files.map((file) => file.id))
      } else {
        setSelectedFiles([])
      }
    },
    [files],
  )

  // 更新全选状态
  useEffect(() => {
    const allSelected =
      files.length > 0 && files.every((file) => selectedFiles.includes(file.id))
    setIsAllSelected(allSelected)
  }, [selectedFiles, files])

  // 更新过滤条件
  const updateFilters = useCallback(
    (key: keyof FilterState, value: string) => {
      const newFilters = {
        ...filters,
        [key]: value,
      }
      setFilters(newFilters)
      setCurrentPage(1) // 重置页码
      // 使用最新的 filters 构建查询
      fetchFiles(buildQuery(1, newFilters, searchText))
    },
    [searchText, filters, fetchFiles, buildQuery],
  )
  const handleButtonClick = (state: string) => {
    updateFilters('public', state)
  }
  const handleShowUpload = () => {
    setEditItem(null)
    setOpenUpload(true)
  }
  const handleEditItem = (fileItem: FileItem) => {
    console.log('fileItem', fileItem)
    setEditItem(fileItem)
    setOpenUpload(true)
  }

  return (
    <div className="w-full h-full flex flex-col mx-auto p-4">
      {/* 顶部搜索和操作区域 */}
      <div className="flex justify-between items-center mb-6">
        <div className="flex items-center gap-2 bg-[#B9AEFF]/10 rounded-2xl border border-[#573CFF]/10 p-1">
          <Button
            className={cn(
              'text-white text-base h-8 rounded-lg hover:bg-primary',
              !filters.public && 'bg-primary',
            )}
            variant="ghost"
            onClick={() => handleButtonClick('')}
          >
            {t('all')}
          </Button>
          <Button
            className={cn(
              'text-white text-base h-8 rounded-lg hover:bg-primary',
              filters.public === '1' && 'bg-primary',
            )}
            variant="ghost"
            onClick={() => handleButtonClick('1')}
          >
            {t('publicResources')}
          </Button>
          <Button
            className={cn(
              'text-white text-base h-8 rounded-lg hover:bg-primary',
              filters.public === '0' && 'bg-primary',
            )}
            variant="ghost"
            onClick={() => handleButtonClick('0')}
          >
            {t('myResources')}
          </Button>
        </div>

        <div className="flex flex-1 items-center justify-end gap-4">
          <div className="relative flex items-center flex-1 px-4 h-10 max-w-md bg-white/10 rounded-xl group border border-transparent focus-within:border-[#A091FD]">
            <div
              onClick={() => handleSearch()}
              className="flex items-center h-full cursor-pointer"
            >
              <Search className="h-5 w-5 text-white" />
            </div>
            <Input
              type="text"
              placeholder={t('search.placeholder')}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  handleSearch()
                }
              }}
              className="border-none bg-transparent text-white placeholder:text-white/40"
            />
          </div>

          {/* 过滤条件 */}
          <Popover>
            <PopoverTrigger asChild>
              <Button
                variant="outline"
                className="flex h-10 bg-white/10 border-none rounded-xl items-center gap-2 hover:bg-white/20"
              >
                <Filter className="h-4 w-4" />
                {t('search.filter')}
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-60 bg-[#06050F] border-[#AEA0FF]/10 rounded-xl p-4">
              <div className="space-y-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium text-white/60">
                    {t('filter.fileType.label')}
                  </label>
                  <Select
                    value={filters.type}
                    onValueChange={(value) => updateFilters('type', value)}
                  >
                    <SelectTrigger className="bg-white/5 text-white border border-transparent data-[state=open]:border-[#A091FD]">
                      <SelectValue placeholder={t('filter.fileType.label')} />
                    </SelectTrigger>
                    <SelectContent className="bg-[#26252E] border-none">
                      <SelectGroup>
                        <SelectItem value="全部">
                          {t('filter.fileType.all')}
                        </SelectItem>
                        <SelectItem value="mp3">
                          {t('filter.fileType.audio')}
                        </SelectItem>
                        <SelectItem value="video">
                          {t('filter.fileType.video')}
                        </SelectItem>
                        <SelectItem value="image">
                          {t('filter.fileType.allImages')}
                        </SelectItem>
                        <SelectItem value="png">
                          {t('filter.fileType.png')}
                        </SelectItem>
                      </SelectGroup>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-medium text-white/60">
                    {t('filter.timeRange.label')}
                  </label>
                  <Select
                    value={filters.timeRange}
                    onValueChange={(value) => updateFilters('timeRange', value)}
                  >
                    <SelectTrigger className="bg-white/5 text-white border border-transparent data-[state=open]:border-[#A091FD]">
                      <SelectValue placeholder={t('filter.timeRange.label')} />
                    </SelectTrigger>
                    <SelectContent className="bg-[#26252E] border-none">
                      <SelectGroup>
                        <SelectItem value="全部">
                          {t('filter.timeRange.all')}
                        </SelectItem>
                        <SelectItem value="今天">
                          {t('filter.timeRange.today')}
                        </SelectItem>
                        <SelectItem value="最近7天">
                          {t('filter.timeRange.last7Days')}
                        </SelectItem>
                        <SelectItem value="最近30天">
                          {t('filter.timeRange.last30Days')}
                        </SelectItem>
                        <SelectItem value="更早">
                          {t('filter.timeRange.earlier')}
                        </SelectItem>
                      </SelectGroup>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-medium text-white/60">
                    {t('filter.sort.label')}
                  </label>
                  <Select
                    value={filters.sortBy}
                    onValueChange={(value) => updateFilters('sortBy', value)}
                  >
                    <SelectTrigger className="bg-white/5 text-white border border-transparent data-[state=open]:border-[#A091FD]">
                      <SelectValue placeholder={t('filter.sort.label')} />
                    </SelectTrigger>
                    <SelectContent className="bg-[#26252E] border-none">
                      <SelectGroup>
                        <SelectItem value="时间降序">
                          {t('filter.sort.timeDesc')}
                        </SelectItem>
                        <SelectItem value="升序">
                          {t('filter.sort.timeAsc')}
                        </SelectItem>
                        <SelectItem value="名称升序">
                          {t('filter.sort.nameAsc')}
                        </SelectItem>
                        <SelectItem value="名称降序">
                          {t('filter.sort.nameDesc')}
                        </SelectItem>
                      </SelectGroup>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <label className="text-sm font-medium text-white/60">
                    {t('filter.tags.label')}
                  </label>
                  <Select
                    value={filters.tags}
                    onValueChange={(value) => updateFilters('tags', value)}
                  >
                    <SelectTrigger className="bg-white/5 text-white border border-transparent data-[state=open]:border-[#A091FD]">
                      <SelectValue placeholder={t('filter.tags.label')} />
                    </SelectTrigger>
                    <SelectContent className="bg-[#26252E] border-none">
                      <SelectGroup>
                        <SelectItem key={'all'} value="all">
                          {t('filter.tags.all')}
                        </SelectItem>
                        {tagList.map((item) => (
                          <SelectItem key={item.id} value={item.name}>
                            {item.name}
                          </SelectItem>
                        ))}
                      </SelectGroup>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </PopoverContent>
          </Popover>

          {selectedFiles.length > 0 ? (
            <>
              <div className="flex items-center gap-2">
                <Checkbox
                  id="select-all"
                  checked={isAllSelected}
                  onCheckedChange={handleSelectAll}
                />
                <label
                  htmlFor="select-all"
                  className="text-sm text-gray-500 whitespace-nowrap cursor-pointer select-none"
                >
                  {t('actions.selectAll')}
                </label>
              </div>
              <Button
                variant="ghost"
                onClick={handleDelete}
                size="sm"
                className="text-gray-500 flex gap-1 items-center"
              >
                <Trash2 className="h-5 w-5" />
                {t('actions.batchDelete')}
                {selectedFiles.length > 0 && `(${selectedFiles.length})`}
              </Button>
            </>
          ) : null}
          <UploadCard
            open={openUpload}
            onOpen={setOpenUpload}
            onSuccess={handleUpload}
            editItem={editItem}
          />
          <Button
            variant="outline"
            className="h-10 bg-[#B9AEFF]/10 hover:bg-[#B9AEFF]/10 border border-[#A091FD] text-white hover:text-[#A091FD] rounded-xl"
            size="sm"
            onClick={handleShowUpload}
          >
            <Upload />
            {t('actions.upload')}
          </Button>
        </div>
      </div>

      {/* 文件列表 */}
      <div className="flex-1 relative overflow-y-auto my-scrollbar">
        <div className="grid grid-cols-5 gap-4 my-scrollbar">
          {files.map((file) => (
            <div
              key={file.id}
              className="relative flex flex-col rounded-lg p-1 group bg-white/5 hover:bg-white/10 transition-colors"
            >
              <div
                className={clsx(
                  'flex absolute top-2 right-2 z-10 group-hover:opacity-100 transition-opacity',
                  selectedFiles.includes(file.id) ? 'opacity-100' : 'opacity-0',
                )}
              >
                <Pencil
                  onClick={() => handleEditItem(file)}
                  size="16"
                  className="mr-2"
                />
                <Checkbox
                  id={`file-${file.id}`}
                  checked={selectedFiles.includes(file.id)}
                  onCheckedChange={(checked) =>
                    handleSelect(file.id, checked as boolean)
                  }
                />
              </div>

              <div
                className="w-full cursor-pointer aspect-square bg-black/40 overflow-hidden rounded-lg flex items-center justify-center"
                onClick={() => handlePreview(file as FileItem)}
              >
                {file.thumbnail ? (
                  file.fileType === 'video' ? (
                    <video
                      className="max-w-full max-h-full bg-black"
                      src={file.url}
                    ></video>
                  ) : (
                    <Image
                      src={file.thumbnail}
                      alt={file.name}
                      width={100}
                      height={200}
                      className="w-full h-full object-contain rounded"
                    />
                  )
                ) : (
                  <div className="w-full h-full bg-black rounded flex items-center justify-center">
                    <span className="text-white">▶</span>
                  </div>
                )}
              </div>

              <div className="p-2.5 pb-0 flex flex-1 flex-col justify-between">
                <div className="text-sm text-white line-clamp-2 break-words overflow-hidden h-10">
                  {file.name}
                </div>
                <div className="flex flex-col items-start">
                  <div className="text-xs text-white/60 pt-1">{file.duration}</div>
                  <div className="flex h-14 items-start flex-nowrap gap-2 py-2.5 w-full scrollbar-thin scrollbar-thumb-white/10 scrollbar-track-transparent overflow-x-auto">
                    <span className="bg-white/10 py-1 px-2 text-[#AEA0FF] rounded-full flex items-center flex-shrink-0 text-xs">
                      <Users size="14" className="mr-1" />
                      {file.public === 1
                        ? t('visibility.public')
                        : t('visibility.private')}
                    </span>
                    {file?.tags &&
                      file.tags.map((item, index) => (
                        <span
                          key={index + '' + item}
                          className="bg-white/10 py-1 px-2 text-[#AEA0FF] rounded-full flex-shrink-0 text-xs"
                        >
                          {item}
                        </span>
                      ))}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 空状态 */}
      {files.length === 0 && (
        <div className="text-center text-gray-500 py-12">
          {searchText ? t('empty.noResults') : t('empty.noFiles')}
        </div>
      )}

      <div className="mt-4">
        <Pagination
          currentPage={currentPage}
          totalPages={totalPages}
          onPageChange={handlePageChange}
        />
      </div>
    </div>
  )
}

export default FileList
